(function () {
    let url = "ws://localhost:3000"; // 连接通信服务器
    let ws = new WebSocket(url);

    const send = document.querySelector('.send');
    const text = document.querySelector('.left-bottom');
    const lt = document.querySelector('.left-top');
    const list = document.querySelector('.right-bottom');

    const username = document.querySelector('.username');
    const password = document.querySelector('.password');
    const lbtn = document.querySelector('.login-send');
    const lwarp = document.querySelector('.login-wrap');
    const wrap = document.querySelector('.wrap');

    let strhtml = '';
    lbtn.onclick = () => {
        if(username.value != '' && password != ''){
            lwarp.style.display = 'none';
            wrap.style.display = 'block';
            ws.send(`{"username":"${username.value}"}`);
        }
    }
    send.onclick = () => {
        ws.send(`{"name":"${username.value}","msg":"${text.value}"}`);
        text.value = '';
    }
    ws.onmessage = function (ev) {
        console.log(ev.data);
        let strhtml1 = '';
        if(ev.data.indexOf('{')==-1){
            let arr = ev.data.split(',');
            for(let i=0;i<arr.length;i++){
                strhtml1 += `
                    <div class="list">
                        <img src="http://www.agri35.com/UploadFiles/img_2_1824621072_4042149756_26.jpg" alt="">
                        <p>${arr[i]}</p>
                    </div>
            `
            list.innerHTML = strhtml1;
            } 
        }else{
            if (ev.data.indexOf('username')!=-1) {
                strhtml += `<div class="login">${JSON.parse(ev.data).username}上线了</div>`
            } else if(JSON.parse(ev.data).name == `${username.value}`) {
                strhtml += `
                <div class="rt">
                    <span><img src="http://www.agri35.com/UploadFiles/img_2_1824621072_4042149756_26.jpg" alt=""></span>
                    <div class="user">${JSON.parse(ev.data).name}</div>
                     <div class="msg">${JSON.parse(ev.data).msg}</div>
                </div>`
            } else {
                strhtml += `
                <div class="lt">
                    <span><img src="http://www.agri35.com/UploadFiles/img_2_1824621072_4042149756_26.jpg" alt=""></span>
                    <div class="user">${JSON.parse(ev.data).name}</div>
                    <div class="msg">${JSON.parse(ev.data).msg}</div>
                </div>`
            }
        }
        lt.innerHTML = strhtml;
    }
})()